﻿using JNPF.Basics.Models;
using JNPF.Data;
using JNPF.Data.Util;
using JNPF.Utils;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace JNPF.Basics.Logic
{
    /// <summary>
    /// 单据规则
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2018-04-20
    /// </summary>
    internal class BillRuleService : DataFactory, BillRuleIService
    {
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<BillRuleEntity>> GetList()
        {
            using (var db = this.Basic)
            {
                return await db.GetIQueryable<BillRuleEntity>().OrderByDescending(o => o.CreatorTime).ToListAsync();
            }
        }
        /// <summary>
        /// 列表分页
        /// </summary>
        /// <param name="requestParam">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<BillRuleEntity>> GetList(PageInput input)
        {
            using (var db = this.Basic)
            {
                var queryWhere = ExtLinq.True<BillRuleEntity>();
                var queryParam = input.queryJson.ToObject();
                if (!string.IsNullOrEmpty(input.keyword))
                {
                    queryWhere = queryWhere.And(m => m.FullName.Contains(input.keyword) || m.EnCode.Contains(input.keyword));
                }
                return await db.GetIQueryable<BillRuleEntity>().Where(queryWhere).OrderByDescending(t => t.CreatorTime).GetPageResultAsync(input);
            }
        }
        /// <summary>
        /// 信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        public async Task<BillRuleEntity> GetInfo(string id)
        {
            using (var db = this.Basic)
            {
                return await db.GetEntityAsync<BillRuleEntity>(m => m.Id == id);
            }
        }
        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="whereLambda">条件</param>
        /// <returns></returns>
        public async Task<bool> IsExist(Expression<Func<BillRuleEntity, bool>> whereLambda)
        {
            using (var db = this.Basic)
            {
                return (await db.GetCountAsync(whereLambda) > 0);
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Delete(BillRuleEntity entity)
        {
            using (var db = this.Basic)
            {
                return await db.DeleteAsync(entity);
            }
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Create(BillRuleEntity entity)
        {
            using (var db = this.Basic)
            {
                return await db.InsertAsync(entity);
            }
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Update(BillRuleEntity entity)
        {
            using (var db = this.Basic)
            {
                return await db.UpdateAsync(entity);
            }
        }

        /// <summary>
        /// 获取流水号
        /// </summary>
        /// <param name="enCode">流水编码</param>
        /// <returns></returns>
        public async Task<string> GetNumber(string enCode)
        {
            StringBuilder strNumber = new StringBuilder();
            using (var db = this.Basic)
            {
                //开启事物
                await db.BeginTransactionAsync();
                var entity = await db.GetEntityAsync<BillRuleEntity>(m => m.EnCode == enCode);
                if (entity != null)
                {
                    //处理隔天流水号归0
                    if (entity.OutputNumber != null)
                    {
                        var serialDate = entity.OutputNumber.Remove(entity.OutputNumber.Length - entity.Digit.ToInt()).Replace(entity.Prefix, "");
                        var thisDate = entity.DateFormat == "no" ? "" : DateTime.Now.ToString(entity.DateFormat);
                        if (serialDate != thisDate)
                        {
                            entity.ThisNumber = 0;
                        }
                        entity.ThisNumber = entity.ThisNumber + 1;
                    }
                    else
                    {
                        entity.ThisNumber = 1;
                    }
                    //拼接单据编码
                    strNumber.Append(entity.Prefix);                                                                  //前缀
                    if (entity.DateFormat != "no")
                    {
                        strNumber.Append(DateTime.Now.ToString(entity.DateFormat));                                  //日期格式
                    }
                    var number = int.Parse(entity.StartNumber) + entity.ThisNumber;
                    strNumber.Append(number.ToString().PadLeft(entity.Digit.ToInt(), '0'));              //流水号

                    //更新流水号
                    entity.OutputNumber = strNumber.ToString();
                    db.Update(entity);

                    //提交事物
                    await db.CommitTransactionAsync();
                }
                else
                {
                    strNumber.Append("单据规则不存在");
                }
            }
            return strNumber.ToString();
        }


    }
}